﻿<%@ Assembly Name="Microsoft.SharePoint.ApplicationPages, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>
<%@ Assembly Name="SharePointPOBox, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b67821a178aa1006" %>
<%@ Page Language="C#" DynamicMasterPageFile="~masterurl/default.master" Inherits="Microsoft.SharePoint.WebControls.LayoutsPageBase" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Import Namespace="SharePointPOBox" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="wssawc" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="wssuc" TagName="InputFormSection" src="~/_controltemplates/InputFormSection.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="InputFormControl" src="~/_controltemplates/InputFormControl.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="ButtonSection" src="~/_controltemplates/ButtonSection.ascx" %>
<script runat="server">
    
    const int iMaxUploadTerm = 5;
    const int iPasswordLength = 16;
    const int iUniqueKeyLength = 40;

    /// <summary>Page.OnLoad</summary>
    /// <param name="e"></param>
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        
        // Set localized string to UI. -----------------------------------
        this.InputSectionLibraryChoiceTitle.Text
            = SharePointPOBox.Common.CurLngStr("SPPOBTicketVendorWebPart_InputSectionLibraryChoiceTitle");
        this.InputSectionLibraryChoiceDesc.Text
            = SharePointPOBox.Common.CurLngStr("SPPOBTicketVendorWebPart_InputSectionLibraryChoiceDesc");

        this.InputSectionExpireTitle.Text
            = SharePointPOBox.Common.CurLngStr("SPPOBTicketVendorWebPart_InputSectionExpireTitle");
        this.InputSectionExpireDesc.Text
            = SharePointPOBox.Common.CurLngStr("SPPOBTicketVendorWebPart_InputSectionExpireDesc");

        this.PurposeTitle.Text
            = SharePointPOBox.Common.CurLngStr("SPPOBPurposeTitle");
        this.PurposeDesc.Text
            = SharePointPOBox.Common.CurLngStr("SPPOBPurposeDesc");

        this.InputSectionResultUploadURLTitle.Text
            = SharePointPOBox.Common.CurLngStr("SPPOBTicketVendorWebPart_InputSectionResultUploadURLTitle");
        this.InputSectionResultUploadURLDesc.Text
            = SharePointPOBox.Common.CurLngStr("SPPOBTicketVendorWebPart_InputSectionResultUploadURLDesc");

        this.InputSectionResultPasswordTitle.Text
            = SharePointPOBox.Common.CurLngStr("SPPOBTicketVendorWebPart_InputSectionResultPasswordTitle");
        this.InputSectionResultPasswordDesc.Text
            = SharePointPOBox.Common.CurLngStr("SPPOBTicketVendorWebPart_InputSectionResultPasswordDesc");

        this.nputSectionResultExpireTitle.Text
            = SharePointPOBox.Common.CurLngStr("SPPOBTicketVendorWebPart_InputSectionResultExpireTitle");
        this.nputSectionResultExpireDesc.Text
            = SharePointPOBox.Common.CurLngStr("SPPOBTicketVendorWebPart_InputSectionResultExpireDesc");

        if(!this.IsPostBack)
        {
            this.EnsureChildControls();
            this.ddlExpire.SelectedIndex = 2;

            string strItemId = Context.Request.QueryString["id"];
            int iItemId;
            if (int.TryParse(strItemId, out iItemId))
            {
                try
                {
                    SPListItem item = Common.ManageList.GetItemByIdAllFields(iItemId);
                    ShowVendedTicketInfo(item);
                }
                catch { }
            }
        }
    }

    /// <summary>CreateChildControls</summary>
    protected override void CreateChildControls()
    {
        base.CreateChildControls();

        // Set target library dropdownlist items. -----------------------------
        this.ddlLibrary.Items.Clear();
        
        // Add default library.
        this.ddlLibrary.Items.Add(new ListItem(SharePointPOBox.Common.CurLngStr("SPPOBUploadLibraryName"), SharePointPOBox.Common.DefaultLibraryURL));

        SPWeb web = SPContext.Current.Site.RootWeb;
        
        foreach (SPList lib in web.Lists)
        {
            if ((!(lib is SPDocumentLibrary))
                || lib.Hidden
                || lib.IsApplicationList
                || lib.IsSiteAssetsLibrary
                || ((SPDocumentLibrary)lib).IsCatalog
                || (lib.RootFolder.Url.ToLower() == SharePointPOBox.Common.DefaultLibraryURL.ToLower())
                || !lib.DoesUserHavePermissions(SPBasePermissions.AddListItems))
            {
                continue;
            }
            // Add lists when current user can add item.
            this.ddlLibrary.Items.Add(new ListItem(lib.Title, lib.RootFolder.Url));
        }
        if (web != null && web != SPContext.Current.Web)
        {
            web.Dispose();
        }


        ddlExpire.Items.Clear();
        for(int i = 1; i <= iMaxUploadTerm; i++)
        {
            ddlExpire.Items.Add(new ListItem(i.ToString() + SharePointPOBox.Common.CurLngStr("SPPOBDayPrefix"), i.ToString()));
        }
    }

    /// <summary>Click event of ok button</summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void OnSubmit(object sender, EventArgs e)
    {
        this.Page.Validate();
        if (this.Page.IsValid)
        {
            // Set deadline date.
            DateTime tmDeadLine = DateTime.Today.AddDays(int.Parse(ddlExpire.SelectedValue));

            // Generate key
            string sUniquekey = SharePointPOBox.Common.GenerateRandomString(iUniqueKeyLength, false);
            string sPassword = SharePointPOBox.Common.GenerateRandomString(iPasswordLength, true);
            
            // Add item to list
            SPList Managelist = SharePointPOBox.Common.ManageList;
            SPListItem item = Managelist.AddItem();
            item[SPBuiltInFieldId.ContentTypeId]
                = new SPContentTypeId(SharePointPOBox.Common.VendedUploadTicketContentTypeId);

            item[Managelist.Fields.GetFieldByInternalName("Title").Id]
                = ddlLibrary.SelectedValue;
            item[Managelist.Fields.GetFieldByInternalName("UploadTicket").Id]
                = sUniquekey;
            item[Managelist.Fields.GetFieldByInternalName("Password").Id]
                = sPassword;
            item[Managelist.Fields.GetFieldByInternalName("UploadDeadline").Id]
                = tmDeadLine;
            item[Managelist.Fields.GetFieldByInternalName("Purpose").Id]
                = txtPurpose.Text;
            //item[Managelist.Fields.GetFieldByInternalName("TicketVendor").Id]
                //= new SPFieldUserValue(SPContext.Current.Web, SPContext.Current.Web.CurrentUser.ID, SPContext.Current.Web.CurrentUser.Name);
            item[Managelist.Fields.GetFieldByInternalName("IsAlreadyUpload").Id]
                = false;

            bool bAllowUnsafeUpdates = item.Web.AllowUnsafeUpdates;
            item.Web.AllowUnsafeUpdates = true;
            item.Update();
            item.Web.AllowUnsafeUpdates = bAllowUnsafeUpdates;
            
            // Show vended ticket info
            ShowVendedTicketInfo(item);
       }
    }

    private void ShowVendedTicketInfo(SPListItem item)
    {
        this.mailtolink.HRef
            = SharePointPOBox.Common.CreateMailToLinkForUpload(item);
        this.mailtolink.Title
            = this.mailtolinkimg.Alt = SharePointPOBox.Common.CurLngStr("SPPOBMailTo");
        this.uploadlink.InnerText
            = this.uploadlink.HRef = SharePointPOBox.Common.CreateUploadURL((string)item[item.Fields.GetFieldByInternalName("UploadTicket").Id]);
        this.passwordlabel.InnerText = (string)item[item.Fields.GetFieldByInternalName("Password").Id];
        this.passwordimg.Attributes["onclick"]
            = this.passwordimg.Attributes["onclick"].Replace("%PasswordLabelId%", this.passwordlabel.ClientID);
        this.Expirelabel.InnerText = ((DateTime)item[item.Fields.GetFieldByInternalName("UploadDeadline").Id]).ToShortDateString();

        this.InputSection.Visible = false;
        this.ResultSection.Visible = true;
        this.btnOK.Visible = false;
        if (this.IsDialogMode)
        {
            ((HtmlInputButton)this.btnSection.FindControl("PlaceHolderButtonCancel").FindControl("BtnCancel")).Value
                = SharePointPOBox.Common.CurLngStr("SPPOBCloseButtonCaption");
        }
    }

    /// <summary>Check target libray.</summary>
    /// <param name="src"></param>
    /// <param name="args"></param>
    protected void ValidateLibrary(object src, ServerValidateEventArgs args)
    {
        SPList lst = SharePointPOBox.Common.GetLibrary(ddlLibrary.SelectedValue, false);
        if (lst == null)
        {
            ((BaseValidator)src).ErrorMessage
                = SharePointPOBox.Common.GetCurrentLangString("viewlsts_L_szNoDocLib2_Text", "wss");
            args.IsValid = false;
        }
        else
        {
            if (lst.DoesUserHavePermissions(SPBasePermissions.AddListItems))
            {
                args.IsValid = true;
            }
            else
            {
                ((BaseValidator)src).ErrorMessage
                    = SharePointPOBox.Common.CurLngStr("SPPOBNoPermissionToUpload");
                args.IsValid = false;
            }
        }
    }
</script>
<asp:Content ID="Content1" contentplaceholderid="PlaceHolderPageTitle" runat="server">
	<SharePoint:EncodedLiteral runat="server" text="<%$Resources:wss,upload_pagetitle%>" EncodeMethod='HtmlEncode'/>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderId="PlaceHolderAdditionalPageHead" runat="server">
<script type="text/javascript">
// <![CDATA[
    function ULSk4d() { var o = new Object; o.ULSTeamName = "Microsoft SharePoint Foundation"; o.ULSFileName = "TicketVendor.aspx"; return o; }
    function _spBodyOnLoad() {
        ULSk4d: ;
    }
    function VerifyCommentLength() {
        ULSk4d: ;
        return true;
    }
    function btnDisabled(set) {
        ULSk4d: ;
        if (set)
            document.getElementById("<%= btnOK.ClientID %>").disabled = true;
        else
            document.getElementById("<%= btnOK.ClientID %>").disabled = false;
    }
    function processInput() {
        ULSk4d: ;
        //btnDisabled(true);
    }
    function ResetSpFormOnSubmitCalled() {
        ULSk4d: ;
        _spFormOnSubmitCalled = false;
        return true;
    }
// ]]>
</script>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">

	<input type="hidden" name="destination" id="destination" value="<asp:Literal ID='Destination' runat='server'/>" />
	<table border="0" width="100%" cellspacing="0" cellpadding="0" class="ms-descriptiontext">
    <Control runat="server" ID="InputSection">
	<wssuc:InputFormSection runat="server">
		<Template_Title>
			<SharePoint:EncodedLiteral ID="InputSectionLibraryChoiceTitle" runat="server" EncodeMethod='HtmlEncode'/>
		</Template_Title>
		<Template_Description>
			<SharePoint:EncodedLiteral ID="InputSectionLibraryChoiceDesc" runat="server" EncodeMethod='HtmlEncode'/>
		</Template_Description>
		<Template_InputFormControls>
			<wssuc:InputFormControl runat="server" LabelAssociatedControlId="ddlLibrary">
			<Template_Control>
			   <table class="ms-authoringcontrols" width="100%">
				<tr><td>
					 <span dir="ltr">
                        <asp:DropDownList runat="server" ID="ddlLibrary" />
					 </span>
				</td></tr>
				<tr><td>
				<asp:CustomValidator Display = "Dynamic" OnServerValidate="ValidateLibrary" runat="server"/>
				</td></tr><tr><td>
				</td></tr>
                </table>
			</Template_Control>
			</wssuc:InputFormControl>
		</Template_InputFormControls>
	</wssuc:InputFormSection>

	<wssuc:InputFormSection runat="server">
		<Template_Title>
			<SharePoint:EncodedLiteral ID="InputSectionExpireTitle" runat="server" EncodeMethod='HtmlEncode'/>
		</Template_Title>
		<Template_Description>
			<SharePoint:EncodedLiteral ID="InputSectionExpireDesc" runat="server" EncodeMethod='HtmlEncode'/>
		</Template_Description>
		<Template_InputFormControls>
			<wssuc:InputFormControl runat="server" LabelAssociatedControlId="ddlExpire">
			<Template_Control>
			   <table class="ms-authoringcontrols" width="100%">
				<tr><td>
					 <span dir="ltr">
                        <asp:DropDownList runat="server" ID="ddlExpire"/>
					 </span>
				</td></tr>
				<tr><td></td></tr><tr><td>
				</td></tr>
                </table>
			</Template_Control>
			</wssuc:InputFormControl>
		</Template_InputFormControls>
	</wssuc:InputFormSection>

	<wssuc:InputFormSection runat="server">
		<Template_Title>
			<SharePoint:EncodedLiteral ID="PurposeTitle" runat="server" EncodeMethod='HtmlEncode'/>
		</Template_Title>
		<Template_Description>
			<SharePoint:EncodedLiteral ID="PurposeDesc" runat="server" EncodeMethod='HtmlEncode'/>
		</Template_Description>
		<Template_InputFormControls>
			<wssuc:InputFormControl runat="server" LabelAssociatedControlId="txtPurpose">
			<Template_Control>
			   <table class="ms-authoringcontrols" width="100%">
				<tr><td>
					<span dir="ltr">
						<asp:TextBox id="txtPurpose" maxlength="255" runat="server"/><br />
					</span>
				</td></tr>
				<tr><td></td></tr><tr><td>
				</td></tr>
                </table>
			</Template_Control>
			</wssuc:InputFormControl>
		</Template_InputFormControls>
	</wssuc:InputFormSection>
    </Control>

    <Control runat="server" ID="ResultSection" visible="false">
	<wssuc:InputFormSection runat="server">
		<Template_Title>
			<SharePoint:EncodedLiteral ID="InputSectionResultUploadURLTitle" runat="server" EncodeMethod='HtmlEncode'/>
		</Template_Title>
		<Template_Description>
			<SharePoint:EncodedLiteral ID="InputSectionResultUploadURLDesc" runat="server" EncodeMethod='HtmlEncode'/>
		</Template_Description>
		<Template_InputFormControls>
			<wssuc:InputFormControl runat="server" LabelAssociatedControlId="mailtolink">
			<Template_Control>
			   <table class="ms-authoringcontrols" width="100%">
				<tr><td>
					 <span dir="ltr">
                        <a runat="server" id="uploadlink" ></a>&nbsp;
                        <a href="" runat="server" id="mailtolink">
                            <img src="/_layouts/images/GMAILNEW.GIF" runat="server" id="mailtolinkimg" style="border:none;" />
                        </a>
					 </span>
				</td></tr>
				<tr><td>
				</td></tr><tr><td>
				</td></tr>
                </table>
			</Template_Control>
			</wssuc:InputFormControl>
		</Template_InputFormControls>
	</wssuc:InputFormSection>

	<wssuc:InputFormSection runat="server">
		<Template_Title>
			<SharePoint:EncodedLiteral ID="InputSectionResultPasswordTitle" runat="server" EncodeMethod='HtmlEncode'/>
		</Template_Title>
		<Template_Description>
			<SharePoint:EncodedLiteral ID="InputSectionResultPasswordDesc" runat="server" EncodeMethod='HtmlEncode'/>
		</Template_Description>
		<Template_InputFormControls>
			<wssuc:InputFormControl runat="server" LabelAssociatedControlId="passwordimg">
			<Template_Control>
			   <table class="ms-authoringcontrols" width="100%">
				<tr><td>
					 <span dir="ltr">
                        <span runat="server" id="passwordlabel"></span>&nbsp;
                        <img runat="server" id="passwordimg" src="/_layouts/images/COPY.GIF" Title="Copy Password to Clipboard!" onclick="clipboardData.setData('Text', document.getElementById('%PasswordLabelId%').innerText);alert('Password was sended to Clipboard!');" />
					 </span>
				</td></tr>
				<tr><td>
				</td></tr><tr><td>
				</td></tr>
                </table>
			</Template_Control>
			</wssuc:InputFormControl>
		</Template_InputFormControls>
	</wssuc:InputFormSection>

	<wssuc:InputFormSection runat="server">
		<Template_Title>
			<SharePoint:EncodedLiteral ID="nputSectionResultExpireTitle" runat="server" EncodeMethod='HtmlEncode'/>
		</Template_Title>
		<Template_Description>
			<SharePoint:EncodedLiteral ID="nputSectionResultExpireDesc" runat="server" EncodeMethod='HtmlEncode'/>
		</Template_Description>
		<Template_InputFormControls>
			<wssuc:InputFormControl runat="server" LabelAssociatedControlId="Expirelabel">
			<Template_Control>
			   <table class="ms-authoringcontrols" width="100%">
				<tr><td>
					 <span dir="ltr">
                        <span runat="server" id="Expirelabel"></span>
					 </span>
				</td></tr>
				<tr><td>
				</td></tr><tr><td>
				</td></tr>
                </table>
			</Template_Control>
			</wssuc:InputFormControl>
		</Template_InputFormControls>
	</wssuc:InputFormSection>
    </Control>

	<wssuc:ButtonSection runat="server" ShowSectionLine="true" TopButtons="false" ID="btnSection">
		<Template_Buttons>
			<input id="btnOK" runat="server" type="button" accesskey="<%$Resources:wss,multipages_okbutton_accesskey%>" class="ms-ButtonHeightWidth" value="<%$Resources:wss,multipages_okbutton_text%>" onclick="processInput();" onserverclick="OnSubmit" />
		</Template_Buttons>
	</wssuc:ButtonSection>
	</table>
</asp:Content>
<%@ Register TagPrefix="wssuc" TagName="TopNavBar" src="~/_controltemplates/TopNavBar.ascx" %>
<asp:Content contentplaceholderid="PlaceHolderTopNavBar" runat="server">
  <wssuc:TopNavBar id="IdTopNavBar" runat="server" Version="4" ShouldUseExtra="true"/>
</asp:Content>
<asp:Content contentplaceholderid="PlaceHolderHorizontalNav" runat="server"/>
<asp:Content contentplaceholderid="PlaceHolderSearchArea" runat="server"/>
<asp:Content contentplaceholderid="PlaceHolderTitleBreadcrumb" runat="server">
  <SharePoint:UIVersionedContent UIVersion="3" runat="server"><ContentTemplate>
	<asp:SiteMapPath
		SiteMapProvider="SPXmlContentMapProvider"
		id="ContentMap"
		SkipLinkText=""
		NodeStyle-CssClass="ms-sitemapdirectional"
		RootNodeStyle-CssClass="s4-die"
		PathSeparator="&#160;&gt; "
		PathSeparatorStyle-CssClass = "s4-bcsep"
		runat="server" />
  </ContentTemplate></SharePoint:UIVersionedContent>
  <SharePoint:UIVersionedContent UIVersion="4" runat="server"><ContentTemplate>
	<SharePoint:ListSiteMapPath
		runat="server"
		SiteMapProviders="SPSiteMapProvider,SPXmlContentMapProvider"
		RenderCurrentNodeAsLink="false"
		PathSeparator=""
		CssClass="s4-breadcrumb"
		NodeStyle-CssClass="s4-breadcrumbNode"
		CurrentNodeStyle-CssClass="s4-breadcrumbCurrentNode"
		RootNodeStyle-CssClass="s4-breadcrumbRootNode"
		HideInteriorRootNodes="true"
		SkipLinkText="" />
  </ContentTemplate></SharePoint:UIVersionedContent>
</asp:Content>
